<template>
  <div class="login">
    <!-- 导航栏 -->
    <van-nav-bar title="黑马头条-登陆" />
    <!-- 表单部分 -->
    <van-form ref="form">
      <van-field
        v-model="mobile"
        label="手机号"
        placeholder="请输入手机号"
        :rules="[{ required: true,  validatorForMobile, message: '请填写用户名', trigger:'onBlur'}]"
      />
      <van-field
        v-model="code"
        label="密码"
        placeholder="请输入密码号"
        :rules="[{ required: true, validatorForCode,message: '请填写密码', trigger:'onBlur'}]"
      />
    </van-form>
    <!-- 登陆按钮 -->
    <div class="btn-wrap">
      <van-button type="info" class="btn" @click="hLogin">登陆</van-button>
    </div>
  </div>
</template>
<script>
import { login } from '@/api/user'
export default {
  data () {
    return {
      mobile: '13912345678', // 手机号
      code: '246810'// 密码
    }
  },
  methods: {
    // 验证不能为空
    validatorForMobile (val) {
      return val !== ''
    },
    // 验证不能为空
    validatorForCode (val) {
      return val !== ''
    },
    // 表格验证
    hLogin () {
      this.$refs.form.validateAll().then((res) => {
        this.hComfirm()
      })
    },
    hComfirm () {
      // 调用封装的接口
      login(this.mobile, this.code).then((res) => {
        console.log(res)
        this.$toast.success('登录成功啦')
        // 保存token
        this.$store.commit('saveToken', res.data.data)
        this.$router.push({
          path: '/'
        })
      }).catch((err) => {
        this.$toast.fail('登录失败啦')
        console.log(err)
      })
    }
  }
}
</script>
<style lang="less" scoped>
.login {
    .btn-wrap {
      padding:20px;
      .btn {
        width: 100%;
        background-color: #6db4fb;
        color: #fff;
      }
    }
}
</style>
